package com.roger.homecenterscreen.data.repository

import com.roger.homecenterscreen.data.api.CalendarApiService
import com.roger.homecenterscreen.data.api.LunarApiService
import com.roger.homecenterscreen.ui.components.HuangliInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.roger.homecenterscreen.config.ApiConfig
import android.util.Log
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import com.nlf.calendar.Solar

class CalendarRepository(
    private val calendarApi: CalendarApiService,
    private val lunarApi: LunarApiService
) {
    
    companion object {
        private const val TAG = "CalendarRepository"
    }
    
    private val juheApiKey = ApiConfig.JUHE_API_KEY
    
    // 根据聚合数据官方文档格式化日期（月份和日期小于10时取个位）
    private fun formatDateForJuheApi(date: String): String {
        val parts = date.split("-")
        if (parts.size == 3) {
            val year = parts[0]
            val month = parts[1].toIntOrNull()?.toString() ?: parts[1] // 去掉前导0
            val day = parts[2].toIntOrNull()?.toString() ?: parts[2]   // 去掉前导0
            return "$year-$month-$day"
        }
        return date
    }

    suspend fun getTodayCalendarInfo(): Result<CalendarInfo> = withContext(Dispatchers.IO) {
        try {
            val today = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Calendar.getInstance().time)
            val formattedDate = formatDateForJuheApi(today)
            Log.i(TAG, "📅 =============== 开始获取万年历数据 ===============")
            Log.i(TAG, "📆 原始日期: $today")
            Log.i(TAG, "📆 格式化日期: $formattedDate (符合聚合数据官方文档格式)")
            Log.i(TAG, "🔑 API Key: ${juheApiKey.take(10)}...${juheApiKey.takeLast(6)}")
            
            // 尝试从聚合数据获取黄历信息
            Log.i(TAG, "📡 调用聚合数据万年历API...")
            val calendarResponse = calendarApi.getCalendarInfo(formattedDate, juheApiKey)
            
            Log.i(TAG, "📊 聚合数据API响应状态: ${if (calendarResponse.isSuccessful) "✅成功" else "❌失败(${calendarResponse.code()})"}")
            
            if (calendarResponse.isSuccessful) {
                val responseBody = calendarResponse.body()
                Log.i(TAG, "📋 API响应代码: ${responseBody?.error_code}")
                Log.i(TAG, "📝 API响应原因: ${responseBody?.reason}")
                
                                 if (responseBody?.error_code == 0) {
                     val calendarData = responseBody.result?.data
                     calendarData?.let { data ->
                         Log.i(TAG, "🎉 聚合数据万年历解析成功!")
                         Log.i(TAG, "   🗓️ 农历: ${data.lunar ?: "未知"}")
                         Log.i(TAG, "   🐲 生肖年: ${data.animalsYear ?: "未知"}")
                         Log.i(TAG, "   🎭 纪年: ${data.lunarYear ?: "未知"}")
                         Log.i(TAG, "   🎊 假日: ${data.holiday ?: "无"}")
                         Log.i(TAG, "   ✅ 宜: ${data.suit ?: "无"}")
                         Log.i(TAG, "   ❌ 忌: ${data.avoid ?: "无"}")
                         Log.i(TAG, "=============== 万年历数据获取成功 (聚合数据) ===============")
                         
                         // 构建完整的农历显示（包含纪年）
                         val fullLunarDate = "${data.lunarYear ?: ""}${data.lunar ?: ""}"
                         
                         return@withContext Result.success(
                             CalendarInfo(
                                 lunarDate = fullLunarDate.ifEmpty { data.lunar ?: "未知农历" },
                                 huangliInfo = HuangliInfo(
                                     suitable = data.suit ?: "暂无信息",
                                     unsuitable = data.avoid ?: "暂无信息"
                                 )
                             )
                         )
                     }
                } else {
                    val errorCode = responseBody?.error_code
                    val reason = responseBody?.reason
                    Log.w(TAG, "❌ 聚合数据API返回错误: 代码=$errorCode, 原因=$reason")
                    
                    // 为特定错误码提供详细说明
                    when (errorCode) {
                        217701 -> {
                            Log.w(TAG, "💡 错误217701解决方案:")
                            Log.w(TAG, "   1. 检查API Key是否有万年历接口权限")
                            Log.w(TAG, "   2. 确认账户余额是否充足")
                            Log.w(TAG, "   3. 验证日期格式: ${formattedDate}")
                            Log.w(TAG, "   4. 联系聚合数据客服确认接口状态")
                        }
                        10001 -> Log.w(TAG, "💡 API Key错误，请检查配置")
                        10002 -> Log.w(TAG, "💡 API Key无权限，请申请万年历接口")
                        10003 -> Log.w(TAG, "💡 API Key已过期，请续费")
                        10012 -> Log.w(TAG, "💡 请求次数超限，请等待或升级套餐")
                        else -> Log.w(TAG, "💡 其他错误，请查阅聚合数据文档")
                    }
                }
            } else {
                Log.w(TAG, "❌ 聚合数据API请求失败: HTTP ${calendarResponse.code()}")
            }
            
            // 如果聚合数据API失败，尝试使用免费的农历API  
            Log.i(TAG, "🔄 降级到免费农历API...")
            val lunarResponse = lunarApi.getLunarInfo(formattedDate)
            
            Log.i(TAG, "📊 免费农历API响应状态: ${if (lunarResponse.isSuccessful) "✅成功" else "❌失败(${lunarResponse.code()})"}")
            
            if (lunarResponse.isSuccessful && lunarResponse.body()?.code == 200) {
                val lunarData = lunarResponse.body()?.data
                lunarData?.let { data ->
                    Log.i(TAG, "🎉 免费农历API解析成功!")
                    Log.i(TAG, "   🗓️ 农历: ${data.lunar}")
                    Log.i(TAG, "   🎭 干支: ${data.ganzhi}")
                    Log.i(TAG, "   🐲 生肖: ${data.shengxiao}")
                    Log.i(TAG, "   ✅ 宜: ${data.yi.joinToString("、")}")
                    Log.i(TAG, "   ❌ 忌: ${data.ji.joinToString("、")}")
                    Log.i(TAG, "=============== 万年历数据获取成功 (免费API) ===============")
                    
                    return@withContext Result.success(
                        CalendarInfo(
                            lunarDate = data.lunar,
                            huangliInfo = HuangliInfo(
                                suitable = data.yi.joinToString("、"),
                                unsuitable = data.ji.joinToString("、")
                            )
                        )
                    )
                }
            } else {
                Log.w(TAG, "❌ 免费农历API也失败")
            }
            
            // 如果所有API都失败，使用离线库计算
            Log.i(TAG, "🔄 所有在线接口失败，改用离线万年历库 6tail/lunar 计算")
            val offlineInfo = getOfflineLunarInfo()
            Log.i(TAG, "📅 离线农历: ${offlineInfo.lunarDate}")
            Log.i(TAG, "✅ 离线宜: ${offlineInfo.huangliInfo.suitable}")
            Log.i(TAG, "❌ 离线忌: ${offlineInfo.huangliInfo.unsuitable}")
            Log.i(TAG, "=============== 万年历数据获取完成 (离线计算) ===============")
            
            Result.success(offlineInfo)
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 万年历数据获取异常", e)
            Log.e(TAG, "=============== 万年历数据获取失败 ===============")
            // 发生异常时，尽力使用离线库；若离线库也异常则回退到简化默认
            return@withContext try {
                Result.success(getOfflineLunarInfo())
            } catch (e2: Exception) {
                Result.success(getDefaultCalendarInfo())
            }
        }
    }
    
    private fun getDefaultCalendarInfo(): CalendarInfo {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1 // Calendar.MONTH 从0开始
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        
        Log.i(TAG, "🗓️ 计算默认农历: ${year}年${month}月${day}日")
        
        // 2025年对应乙巳年，根据当前日期估算农历
        val lunarYear = when (year) {
            2025 -> "乙巳年"
            2024 -> "甲辰年" 
            2026 -> "丙午年"
            else -> "乙巳年" // 默认使用2025年
        }
        
        // 简化农历计算：7月21日大约对应农历六月廿七
        val lunarMonths = listOf(
            "正月", "二月", "三月", "四月", "五月", "六月",
            "七月", "八月", "九月", "十月", "十一月", "十二月"
        )
        
        val lunarDays = listOf(
            "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
            "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
            "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
        )
        
        // 基于实际日期的简化农历计算
        val lunarMonth = when (month) {
            1 -> "腊月"  // 1月通常还是上年腊月
            2 -> "正月"
            3 -> "二月" 
            4 -> "三月"
            5 -> "四月"
            6 -> "五月"
            7 -> "六月"  // 7月对应农历六月
            8 -> "七月"
            9 -> "八月"
            10 -> "九月"
            11 -> "十月"
            12 -> "十一月"
            else -> "六月"
        }
        
        // 简化日期计算：7月21日 ≈ 六月廿七
        val lunarDay = when {
            day <= 5 -> lunarDays[day + 20] // 廿一到廿五
            day <= 15 -> lunarDays[day - 5] // 初一到初十
            day <= 25 -> lunarDays[day - 5] // 十一到二十
            else -> lunarDays[day - 5] // 廿一以后
        }
        
        val lunarDate = "${lunarYear}${lunarMonth}${lunarDay}"
        
        Log.i(TAG, "📅 生成默认农历: $lunarDate")
        
        // 简化的黄历信息
        val suitableOptions = listOf(
            "出行、开业、结婚",
            "祭祀、祈福、入宅", 
            "开工、签约、交易",
            "学习、考试、会友",
            "理财、投资、购物",
            "运动、健身、休息"
        )
        
        val unsuitableOptions = listOf(
            "搬家、装修、动土",
            "手术、治疗、开刀",
            "争吵、诉讼、冲突", 
            "破财、借贷、赌博",
            "熬夜、暴饮、暴食",
            "重大决策、冒险"
        )
        
        val suitableIndex = day % suitableOptions.size
        val unsuitableIndex = (day + 3) % unsuitableOptions.size
        
        return CalendarInfo(
            lunarDate = lunarDate,
            huangliInfo = HuangliInfo(
                suitable = suitableOptions[suitableIndex],
                unsuitable = unsuitableOptions[unsuitableIndex]
            )
        )
    }

    private fun getOfflineLunarInfo(): CalendarInfo {
        val cal = Calendar.getInstance()
        val year = cal.get(Calendar.YEAR)
        val month = cal.get(Calendar.MONTH) + 1
        val day = cal.get(Calendar.DAY_OF_MONTH)
        val solar = Solar(year, month, day)
        val lunar = solar.lunar

        val lunarDate = lunar.toString() // e.g. 二〇二五年七月初六
        val yi = lunar.getDayYi().joinToString("、").ifBlank { "宜：无明显宜事" }
        val ji = lunar.getDayJi().joinToString("、").ifBlank { "忌：无明显忌事" }

        return CalendarInfo(
            lunarDate = lunarDate,
            huangliInfo = HuangliInfo(
                suitable = yi,
                unsuitable = ji
            )
        )
    }
}

data class CalendarInfo(
    val lunarDate: String,
    val huangliInfo: HuangliInfo
) 